﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;

public class DiagnosticsHelper
{
    /// <summary>
    /// 进程是否存在
    /// </summary>
    /// <param name="procesName">进程名</param>
    /// <returns></returns>
    public bool isExist(string procesName)
    {
        Process[] proc = Process.GetProcessesByName(procesName);
        if (proc.Length == 0)
            return false;
        else
            return true;
    }

    /// <summary>
    /// 关闭进程
    /// </summary>
    /// <param name="processName">进程名</param>
    public void KillProcess(string processName)
    {
        Process[] myproc = Process.GetProcesses();
        foreach (Process item in myproc)
        {
            if (item.ProcessName == processName)
            {
                item.Kill();
            }
        }
    }
    /// <summary>
    /// 强制关闭最近打开的某个进程
    /// </summary>
    /// <param name="processName">进程名</param>
    public void KillRecentProcess(string processName)
    {
        System.Diagnostics.Process[] Proc = System.Diagnostics.Process.GetProcessesByName(processName);
        System.DateTime startTime = new DateTime();
        int m, killId = 0;
        for (m = 0; m < Proc.Length; m++)
        {
            if (startTime < Proc[m].StartTime)
            {
                startTime = Proc[m].StartTime;
                killId = m;
            }
        }
        if (Proc[killId].HasExited == false)
        {
            Proc[killId].Kill();
        }

    }

    /// <summary>
    /// 进程信息
    /// </summary>
    /// <param name="procesName">进程名</param>
    /// <returns>Name,PID,Path</returns>
    public DataTable getProssInfo(string procssName)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("PID", typeof(int));
        dt.Columns.Add("Path", typeof(string));

        foreach (Process p in Process.GetProcesses())
        {
            if (!string.IsNullOrEmpty(procssName) && p.ProcessName != procssName)
                continue;
            //
            DataRow dr = dt.NewRow();
            dr["Name"] = p.ProcessName;
            dr["PID"] = p.Id;
            //if (p.MainWindowHandle == IntPtr.Zero)
            //    dr["Path"] ="";
            //else
            //    dr["Path"] =  p.MainModule.FileName;
            try { dr["Path"] = p.MainModule.FileName; }
            catch { continue; }
            dt.Rows.Add(dr);
        }
        //
        return dt;
    }
    /// <summary>
    /// 进程信息
    /// </summary>
    /// <param name="procesName">进程名</param>
    /// <returns>Name,PID,Path</returns>
    public DataTable getProssInfo()
    {
        return getProssInfo("");
    }

}
